#!/bin/bash
#功能：limit控制项,修改/etc/security/limits.conf

USER_NAME='*'
SRC_FILE=/etc/security/limits.conf
#######################################################################

#SH
SHPATH=`readlink -f $0`
SHDIR=`dirname $SHPATH`
SHNAME="$0"

#DIR
LOG_DIR=$SHDIR/logs/$SHNAME
TMP_DIR=$SHDIR/temp/$SHNAME
mkdir -p $LOG_DIR $TMP_DIR

#bak
if [ ! -f "$SRC_FILE.init.bak" ];then cp $SRC_FILE $SRC_FILE.init.bak ;fi

#
cat <<EOF > $TMP_DIR/update.txt
soft nproc 655650 
hard nproc 655650 
sofr stack 614400 
hard stack 614400 
sofr nofile 655360 
hard nofile 655360
sofr memlock unlimited 
hard memlock unlimited 
sofr core unlimited 
hard core unlimited
EOF

while read LINE
do
	LINE_VAR1=$USER_NAME
	LINE_VAR2=`echo $LINE|awk '{print $1}'`
	LINE_VAR3=`echo $LINE|awk '{print $2}'`
	LINE_VAR4=`echo $LINE|awk '{print $3}'`

	cat $SRC_FILE|wc -l |xargs seq >$TMP_DIR/src_ln.txt
	LINE_NUM=`paste $SRC_FILE $TMP_DIR/src_ln.txt |grep -v ^# |awk -v var1=$LINE_VAR1  '$1==var1 {print}'|awk -v var2=$LINE_VAR2  '$2==var2 {print}'|awk -v var3=$LINE_VAR3  '$3==var3 {print}'|awk -v var4=$LINE_VAR4  '$4==var4 {print}'|awk '{print $NF}'`
	if [ -z "$LINE_NUM" ];then
		echo "$LINE_VAR1 $LINE_VAR2 $LINE_VAR3 $LINE_VAR4" >> $SRC_FILE
		if [ $? -eq 0 ];then echo "Success,FILE=$SRC_FILE 添加策略: $LINE_VAR1 $LINE_VAR2 $LINE_VAR3 $LINE_VAR4 成功。";else echo "Error!FILE=$SRC_FILE  添加策略: $LINE_VAR1 $LINE_VAR2 $LINE_VAR3 $LINE_VAR4 失败！请检测文件权限，或使用root用户重试！";fi
	else
		for i in `echo $LINE_NUM`
		do
			DIFF_VAR=`sed -n ${i}p $SRC_FILE | sed "s/$LINE_VAR1//g" |sed "s/$LINE_VAR2//g"|sed "s/$LINE_VAR3//g"|tr -d " " |sed "s/$LINE_VAR4//g"|tr -d " "`
			if [ -z "$DIFF_VAR" ];then
				echo "TIP,FILE=$SRC_FILE 已存在策略: $LINE_VAR1 $LINE_VAR2 跳过操作。"
			else
				sed -i "$i s/^/#/" $SRC_FILE
				sed -i "${i}a $LINE_VAR1 $LINE_VAR2 $LINE_VAR3 $LINE_VAR4" $SRC_FILE
				if [ $? -eq 0 ];then echo "Success,FILE=$SRC_FILE 添加策略: $LINE_VAR1 $LINE_VAR2 $LINE_VAR3 $LINE_VAR4 成功。";else echo "Error!FILE=$SRC_FILE  添加策略: $LINE_VAR1 $LINE_VAR2 $LINE_VAR3 $LINE_VAR4 失败！请检测文件权限，或使用root用户重试！";fi
			fi
		done
	fi
done <$TMP_DIR/update.txt


#生效
#source /etc/security/limits.conf